#!/usr/bin/env python
# -*- coding: utf-8 -*-

'''
@File    : settings.py
@Description : 配置读取模块，用于读取config.ini中的配置项
'''

import os
import configparser
from typing import Dict, Any, Optional


class Config:
    """
    配置类，用于读取配置文件中的配置项
    """
    def __init__(self, config_file: str = None):
        """
        初始化配置类
        
        Args:
            config_file: 配置文件路径，默认为None，使用默认配置文件路径
        """
        # 项目根目录
        self.root_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
        
        # 配置文件路径
        if config_file is None:
            self.config_file = os.path.join(self.root_dir, 'config', 'config.ini')
        else:
            self.config_file = config_file
        
        # 解析配置文件
        self.config = configparser.ConfigParser()
        self.config.read(self.config_file, encoding='utf-8')
        
        # 环境配置
        self.environment = self.get_config('env', 'environment')
        
        # 基础URL
        self.base_url = self.get_config('url', f'{self.environment}_base_url')
        
        # 日志配置
        self.log_level = self.get_config('log', 'level')
        self.log_backup_count = int(self.get_config('log', 'backup_count'))
        self.log_dir = os.path.join(self.root_dir, 'logs')
        
        # 钉钉配置
        self.dingtalk_webhook = self.get_config('dingtalk', 'webhook')
        self.dingtalk_secret = self.get_config('dingtalk', 'secret')
        
        # 邮件配置
        self.smtp_server = self.get_config('email', 'smtp_server')
        self.smtp_port = int(self.get_config('email', 'smtp_port'))
        self.email_sender = self.get_config('email', 'sender')
        self.email_password = self.get_config('email', 'password')
        self.email_receivers = self.get_config('email', 'receivers').split(',')
        
        # 报告配置
        self.report_dir = os.path.join(self.root_dir, self.get_config('report', 'report_dir'))
        self.allure_results_dir = os.path.join(self.root_dir, self.get_config('report', 'allure_results_dir'))
        self.html_report_dir = os.path.join(self.root_dir, self.get_config('report', 'html_report_dir'))
        
        # 测试数据目录
        self.data_dir = os.path.join(self.root_dir, 'data')
    
    def get_config(self, section: str, option: str, default: Any = None) -> Optional[str]:
        """
        获取配置项的值
        
        Args:
            section: 配置节
            option: 配置项
            default: 默认值，当配置项不存在时返回默认值
            
        Returns:
            配置项的值，如果配置项不存在则返回默认值
        """
        try:
            return self.config.get(section, option)
        except (configparser.NoSectionError, configparser.NoOptionError):
            return default
    
    def get_all_config(self) -> Dict[str, Dict[str, str]]:
        """
        获取所有配置项
        
        Returns:
            所有配置项的字典
        """
        result = {}
        for section in self.config.sections():
            result[section] = {}
            for option in self.config.options(section):
                result[section][option] = self.config.get(section, option)
        return result


# 创建全局配置对象
config = Config()


if __name__ == '__main__':
    # 测试配置读取
    print(f"环境: {config.environment}")
    print(f"基础URL: {config.base_url}")
    print(f"日志级别: {config.log_level}")
    print(f"钉钉Webhook: {config.dingtalk_webhook}")